<?php

namespace App\Controllers\Notify;

use \App\Libs\Pay\PayLibs;
use \App\Models\Order\Order;
use \App\Models\Order\PailebaoOrder;
use App\Libs\Log\Logger;

class AlipayNotify extends \App\Libs\Base\BaseAction
{

    protected function beforeRun()
    {
        parent::beforeRun();
//        $this->needLogin = TRUE;
    }

    //专用支付之后的回调
    public function execute()
    {

        $msgbefore = '
';
//        $msg = $msgbefore . var_export($_POST, true);
//        Logger::info('AlipayNotity', $msg);

        $post = $this->request->getPost();
        $alipay = new PayLibs(1, true);
        //验证是否是！！支付宝！！发给我的
        $flag = $alipay->alipay_notify($post);
        if ($flag) {
            //验证支付逻辑
            $out_trade_no = $post['out_trade_no'];
            //交易状态：字符串
            $trade_status = $post['trade_status'];
            //交易额
            $total_amount = $post['total_amount'];
            $pass_params = json_decode(urldecode($post['passback_params']));

            $appId = $post['app_id'];
            //1 ：验证appid
            $alipayInfo = Config::instance()->pay['alipay'];
            if ($alipayInfo['appId'] != $appId) {
                echo 'failure';
            }
            //2 ： 验证seller_email
            if ($alipayInfo['seller_email'] != $post['seller_email']) {
                echo 'failure';
            }
            //3 : 验证是否有此订单号码,分为：charge，充值派乐宝，买东西，buy
            if ($pass_params->type == 'charge') {
                $matchOrder = PailebaoOrder::find([
                    'conditions' => 'order_sn=?1',
                    'bind' => [1 => $out_trade_no]
                ]);
                if (empty($matchOrder)) {
                    //todo：：记录，提醒管理员
//                    Logger::info('receivedErrorNotifyMsg', );
                    echo 'failure';
                }
                //4 : 验证订单金额是否是正确的
                if ($matchOrder->money_num != $total_amount) {
                    //todo：：记录有一单金额不对
                    echo 'failure';
                }
            } elseif ($pass_params->type == 'buy') {
                $matchOrder = Order::find([
                    'conditions' => 'order_sn=?1',
                    'bind' => [1 => $out_trade_no]
                ]);
                if (empty($matchOrder)) {
                    echo 'failure';
                }
                //4 : 验证订单金额是否是正确的
                if ($matchOrder->price != $total_amount) {
                    echo 'failure';
                }
            }

            //官方文档4步验证完成，

            //确定交易状态，更改订单状态
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {

//             是否已支付 0:待支付  1:已支付 2:已取消 3.已过期 4.已失效 5.已使用 6.已退款 9.异常
                //对于买东西的订单表
                if ($pass_params->type == 'buy') {
                    if ($matchOrder->status == '0') {
                        $matchOrder->status = '1';
                        $matchOrder->buy_info = json_encode($post);
                        $res = $matchOrder->update();
                        if ($res) {
                            echo 'success';
                        } else {
                            echo 'failure';
                            //todo::写日志：说明此订单已支付成功但是，更改数据库失败;
                        }
                    } else {
                        //todo：：记录相应订单号，状态有误;应该是待支付状态;代号：0
                        echo 'failure';
                    }
                } elseif ($pass_params->type == 'charge') {
                    if ($matchOrder->order_status == '0') {
                        $matchOrder->order_status = '1';
                        $matchOrder->charge_info = json_encode($post);
                        $res = $matchOrder->update();
                        if ($res) {
                            echo 'success';
                        } else {
                            echo 'failure';
                            //todo::写日志：说明此订单已支付成功但是，更改数据库失败;
                        }
                    } else {
                        //todo：：记录相应订单号，状态有误;应该是待支付状态;代号：0
                        echo 'failure';  //本地库状态不是待支付，状态有问题！！！
                    }
                }

            } elseif ($trade_status == 'TRADE_CLOSED') {
                $matchOrder->status = '2';
                $res = $matchOrder->update();
                if ($res) {
                    echo 'success';
                } else {
                    echo 'failure';
                }
            }
        } else {
            //验签失败
            echo 'failure';
        }
        exit;
    }

}
